package top.majuan.study.study.servlet.software;

import top.majuan.study.study.dao.TbsoftwareDAO;
import top.majuan.study.study.dao.TbsoftwaretypeDAO;
import top.majuan.study.study.entity.Result;
import top.majuan.study.study.entity.Tbsoftware;
import top.majuan.study.study.entity.Tbsoftwaretype;
import top.majuan.study.study.util.JsonUtils;
import top.majuan.study.study.util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "softwaremodify", urlPatterns = "/software/modify.action")
public class ModifyServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        text/plain
        resp.setContentType("application/json");
        PrintWriter writer = resp.getWriter();
//       获取请求中的软件类别数据
        Integer id = Integer.parseInt(req.getParameter("id"));
        Integer type_id = Integer.parseInt(req.getParameter("type_id"));
        String software_name = req.getParameter("software_name");
        String description = req.getParameter("description");
        String vendor = req.getParameter("vendor");
//        基础数据校验
        if (StringUtil.isBlank(software_name)) {
            Result<String> result = Result.fail("软件信息不能为空", null);
            writer.println(JsonUtils.stringify(result));
            return;
        }
        if (StringUtil.isBlank(description)) {
            Result<String> result = Result.fail("软件信息描述不能为空", null);
            writer.println(JsonUtils.stringify(result));
            return;
        }

        Tbsoftware software = new Tbsoftware();
        software.setId(id);
        software.setSoftware_name(software_name);
        software.setDescription(description);
        software.setType_id(type_id.toString());
        software.setVendor(vendor);



//        修改到软件信息表
        try {
             int i = TbsoftwareDAO.update(software);
             if (i == 1) {
                 Result<String> result = Result.success("修改成功");
                 writer.println(JsonUtils.stringify(result));
             } else {
                 Result<String> result = Result.fail("修改失败", null);
                 writer.println(JsonUtils.stringify(result));
             }
        } catch (Exception e) {
            e.printStackTrace();
            Result<String> result = Result.fail("修改发生错误", null);
            writer.println(JsonUtils.stringify(result));
        }

    }
}
